package org.agile4j.architecture.order.service;

import org.agile4j.architecture.cartmgr.service.ICartService;
import org.agile4j.architecture.cartmgr.vo.CartModel;
import org.agile4j.architecture.cartmgr.vo.CartQueryModel;
import org.agile4j.architecture.order.dao.OrderDAO;
import org.agile4j.architecture.order.vo.OrderDetailModel;
import org.agile4j.architecture.order.vo.OrderModel;
import org.agile4j.architecture.order.vo.OrderQueryModel;
import org.agile4j.architecture.store.service.IStoreService;
import org.agile4j.architecture.store.vo.StoreModel;
import org.agile4j.common.service.BaseService;
import org.agile4j.common.utils.page.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService extends BaseService<OrderModel, OrderQueryModel> implements IOrderService {

	private OrderDAO orderDAO ;
	@Autowired
	public void setOrderDAO(OrderDAO orderDAO) {
		this.orderDAO = orderDAO;
		super.setDao(orderDAO);
	}
	
	@Autowired
	private IOrderDetailService orderDetailService ;
	
	@Autowired
	private IStoreService storeService ;
	
	@Autowired
	private ICartService cartService ;

	@Override
	public void order(Integer customerUuid) {
		//1:查出这个人购物车所有的信息
		CartQueryModel cqm  = new CartQueryModel() ;
		cqm.getPage().setRowCount(1000);
		cqm.setCustomerUuid(customerUuid);
		Page<CartModel> page = cartService.getByConditionPage(cqm) ;
		//2:保存主订单
		double totalMoney = 0.0d ;
		for (CartModel cartModel : page.getResult()) {
			totalMoney += 10d;
		}
		OrderModel order = new OrderModel() ;
		order.setCustomerUuid(customerUuid);
		order.setOrderTime(String.valueOf(System.currentTimeMillis()));
		order.setSaveMoney(0.0d);
		order.setTotalMoney(totalMoney);
		order.setState(1);
		
		orderDAO.create(order);
		//3:保存详细订单
		for (CartModel cartModel : page.getResult()) {
			OrderDetailModel odm = new OrderDetailModel();
			odm.setGoodsUuid(cartModel.getGoodsUuid());
			odm.setOrderNum(cartModel.getBuyNum());
			odm.setPrice(10.0d);
			odm.setMoney(odm.getPrice() * odm.getOrderNum());
			odm.setSaveMoney(0.0d);
			odm.setOrderUuid(order.getUuid());
			orderDetailService.create(odm);
			
			//4:修改库存
			StoreModel storeModel = storeService.getByGoodsUuid(cartModel.getGoodsUuid());
			storeModel.setStoreNum(storeModel.getStoreNum() - odm.getOrderNum());
			storeService.update(storeModel);
			
			//5:清空购物车
			cartService.delete(cartModel.getUuid());
		}
	}
}
